package com.example.waterorder.tools;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class JwtHelper {

    //过期时间
    public static final long tokenExpiration = 60 * 60 * 1000L;// 60 * 60 *1000  一个小时
    //签名秘钥
    public static final String tokenSignKey = "water_order";

    //根据参数生成token
    public static String createToken(String openId) {
        String token = Jwts.builder()
                .setSubject("USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("openId", openId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //根据token字符串得到用户openID
    public static String getUserId(String token) {
        if (!StringUtils.isNotBlank(token)) {
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("openId");
    }


    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public static Boolean isTokenExpired(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Date expiration = claimsJws.getBody().getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }



    //根据token字符串得到用户名称
    public static String getUserName(String token) {
        if (StringUtils.isBlank(token)) return "";

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("userName");
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken("11223");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));

    }
}

